"""
聊天室客户端
"""
from socket import *
from multiprocessing import Process

# 服务端地址
ADDR = ("127.0.0.1", 8888)


def do_login(sock):
    while True:
        name = input("Name:")  # 输入姓名
        msg = "LOGIN " + name  # 组织请求结构
        sock.sendto(msg.encode(), ADDR)  # 发请求
        result, addr = sock.recvfrom(128)  # 等结果
        if result == b"OK":
            print("您已进入聊天室")
            return name
        else:
            print("该用户已存在")


# 接收消息打印
def recv_msg(sock):
    while True:
        data, addr = sock.recvfrom(1024 * 1024)
        # 重新组织打印结构
        msg = '\n' + data.decode() + "\n发言:"
        print(msg, end='')


# 循环输入发送 (过程中可以退出)
def send_msg(sock, name):
    while True:
        try:
            content = input("发言:")
        except KeyboardInterrupt:
            content = "exit"
        if content == 'exit':
            msg = "EXIT " + name
            sock.sendto(msg.encode(), ADDR)
            break  # 结束循环
        msg = "CHAT %s %s" % (name, content)
        sock.sendto(msg.encode(), ADDR)


# 启动客户端 （与服务端配合）
def main():
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(("0.0.0.0", 23455))  # 非常规操作，保持客户端端口不变
    # 一步一步来做
    name = do_login(sock)
    # 创建子进程
    p = Process(target=recv_msg, args=(sock,), daemon=True)
    p.start()
    send_msg(sock, name)  # 父进程执行


if __name__ == '__main__':
    main()
